package com.coolweather.android;


import static com.coolweather.android.constants.Constants.AQI_URL;
import static com.coolweather.android.constants.Constants.FORECAST_URL;
import static com.coolweather.android.constants.Constants.KEY;
import static com.coolweather.android.constants.Constants.NOWWEATHER_URL;
import static com.coolweather.android.constants.Constants.PIC_URL;
import static com.coolweather.android.constants.Constants.SUGGEST_URL;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.coolweather.android.databinding.ActivityMainBinding;
import com.coolweather.android.databinding.ActivityWeatherBinding;
import com.coolweather.android.databinding.ForecastItemBinding;
import com.coolweather.android.gson.AQI;
import com.coolweather.android.gson.BingPic;
import com.coolweather.android.gson.Forecast;
import com.coolweather.android.gson.NowWeather;
import com.coolweather.android.gson.Suggest;
import com.coolweather.android.util.HttpUtil;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
    ActivityWeatherBinding binding;
    @Override
    protected void onCreate(Bundle saveInstanceState){
        super.onCreate(saveInstanceState);
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        binding = ActivityWeatherBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Intent intent = getIntent();


        String spot = intent.getStringExtra("spot");
        String location = intent.getStringExtra("location");
        Log.d("test2", "onCreate: "+spot+":"+location);

        showTitle(spot);
        requestWeather(location);
        loadBingPic();
    }

    private void loadBingPic() {
        HttpUtil.sendOkHttpRequest(PIC_URL, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                runOnUiThread(()->{
                    Toast.makeText(WeatherActivity.this,"访问每日一图失败",Toast.LENGTH_SHORT).show();

                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            //step1:拿到响应数据
            String strJson = response.body().string();
                Log.d("test", "onResponse: "+strJson);
                //step2:尝试去解析数据
                BingPic bingPic = gson.fromJson(strJson,BingPic.class);
                if (bingPic!=null&& bingPic.getCode()==200){
                    runOnUiThread(()->{
                        Glide.with(WeatherActivity.this).load(bingPic.getData().getUrl()).into(binding.bingPicImg);
                    });
                }


            }
        });
    }

    private void requestWeather(String location) {
        String url = String.format(NOWWEATHER_URL,location);
        Log.d("test", "request aqi: "+url);
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            String strJson = response.body().string();
            NowWeather nowWeather = gson.fromJson(strJson,NowWeather.class);
            if (nowWeather.getCode().equals("200")){
                Log.d("test", String.format("当前气温：%s ℃，天气情况：%s",
                        nowWeather.getNow().getTemp(),
                        nowWeather.getNow().getText()));
                showNowWeather(nowWeather);
            }else{
                Log.d("test", "访问实时天气API出错 ");
            }
            }
        });

        String url_aqi = String.format(AQI_URL,location,KEY);
        Log.d("test", "request aqi: "+url_aqi);
        HttpUtil.sendOkHttpRequest(url_aqi, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String strJson = response.body().string();
                AQI aqi = gson.fromJson(strJson,AQI.class);
                if (aqi.getCode().equals("200")){
                    Log.d("test", String.format("当前AQI：%s ℃，PM2.5：%s",
                            aqi.getNow().getAqi(),
                            aqi.getNow().getPm2p5()));
                    showAQI(aqi);
                }else{
                    Log.d("test", "访问实时天气API出错 ");
                }
            }
        });

        String url_suggest = String.format(SUGGEST_URL,location,KEY);
        Log.d("test", "request suggest: "+url_suggest);
        HttpUtil.sendOkHttpRequest(url_suggest, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String strJson = response.body().string();
                Suggest suggest = gson.fromJson(strJson, Suggest.class);
                if (suggest.getCode().equals("200")){
                    showSuggest(suggest);
                }else{
                    Log.d("test", "访问生活建议时出错 ");
                }
            }
        });

        String url_forecast = String.format(FORECAST_URL,location,KEY);
        Log.d("test", "request forecast: "+url_forecast);
        HttpUtil.sendOkHttpRequest(url_forecast, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String strJson = response.body().string();
                Forecast forecast = gson.fromJson(strJson, Forecast.class);
                if (forecast.getCode().equals("200")){
                    showForecast(forecast);
                }else{
                    Log.d("test", "访问未来7天的API时出错 ");
                }
            }
        });


    }

    private void showForecast(Forecast forecast) {

        runOnUiThread(()->{
            //拿到显示未来七天天气的容器组件
            if (forecast!=null&&forecast.getCode().equals("200")){
                binding.includeForecast.forecastLayout.removeAllViews();
                //遍历每一天的天气
                for (Forecast.DailyDTO dailyDTO : forecast.getDaily()){
                    ForecastItemBinding binding_item = ForecastItemBinding.inflate(getLayoutInflater());
                    binding_item.dateText.setText(dailyDTO.getFxDate());
                    binding_item.infoText.setText(dailyDTO.getTextDay());
                    binding_item.maxText.setText(dailyDTO.getTempMax());
                    binding_item.minText.setText(dailyDTO.getTempMin());
                    View child = binding_item.getRoot();
                    binding.includeForecast.forecastLayout.addView(child);

                }
                //每一次遍历，加载子项布局
                //在子项布局中的组件上分别设上数据
                //把子项布局添加到未来七天的容器组件上


            }

        });
    }

    private void showSuggest(Suggest suggest) {
        runOnUiThread(()->{
            binding.includeSuggestion.wearText.setText(suggest.getDaily().get(0).getText());
            binding.includeSuggestion.sportText.setText(suggest.getDaily().get(1).getText());
            binding.includeSuggestion.comfortText.setText(suggest.getDaily().get(2).getText());
        });
    }

    private void showAQI(AQI aqi) {
        runOnUiThread(()->{
            binding.includeAqi.aqiText.setText(aqi.getNow().getAqi());
            binding.includeAqi.pm25Text.setText(aqi.getNow().getPm2p5());

        });
    }

    private void showNowWeather(NowWeather nowWeather) {
        runOnUiThread(()->{
            binding.includeNow.degreeText.setText(nowWeather.getNow().getTemp()+"℃");
            binding.includeNow.weatherInfoText.setText(nowWeather.getNow().getText());
        });
    }

    Gson gson = new Gson();

    private void showTitle(String spot) {
        binding.includeTitle.titleCity.setText(spot);
        SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd hh:mm:ss");
        binding.includeTitle.titleUpdateTime.setText(format.format(new Date()));
    }

}
